<?php

namespace App\Repository\UpThree;

use App\Api\Transfer;
use App\Jobs\BigData;
use App\Jobs\GetOrderStatus;
use App\Repository\Admin\AdminUsersLogRepository;
use App\Repository\AppUser\TouTiaoPayOrderRepository as douyinPayModel;
use App\Repository\AppUser\TouTiaoRepository as TouTiaoUser;
use App\Repository\AppUser\TouTiaoUserOrderRepository;
use App\Repository\BaseRepository;
use App\Repository\GetWay\WayRepository;
use App\Repository\Order\OrderChannelRepository;
use App\Repository\Order\OrderProductRepository;
use App\Repository\Order\OrderRepository;
use App\Repository\Orders\OrdersOldRepository;
use App\Repository\Orders\OrdersRepository;
use App\Repository\Product\GoodsRepository;
use App\Repository\Product\ProductRepository;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class GetOrderStatusDataRepostition extends BaseRepository
{
    private $goodsModel;
    private $productModel;
    private $orderProductModel;
    private $channelModel;
    private $orderModel;
    private $log;
    private $userMoneyLog;
    private $logOrdersOld;
    private $logOrdersVar;
    private $isManyOrders;

    public function __construct()
    {
        ini_set('max_execution_time', 300);
        $this->goodsModel = new GoodsRepository();
        $this->productModel = new ProductRepository();
        $this->orderProductModel = new OrderProductRepository();
        $this->channelModel = new OrderChannelRepository();
        $this->orderModel = new OrderRepository();
        $this->userMoneyLog = new AdminUsersLogRepository();
        $this->log = new Logger('getOrderSataus');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/getOrderSataus.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->logOrdersOld = new Logger('orderUpordersOld');
        $this->logOrdersOld->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/orderUpordersOld.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->logOrdersVar = new Logger('orderUpordersVar');
        $this->logOrdersVar->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/orderUpordersVar.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->isManyOrders = new Logger('isManyOrders');
        $this->isManyOrders->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/isManyOrders.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }

    public function index()
    {
    }

    public function getAllOrderStatus($data = array())
    {
        $res = DB::table('system')->where('name', 'td_array')->first();
        if (!empty($res) && !empty($res->val)) {
            $ex = explode(",", $res->val);
            if (!empty($ex)) {
                foreach ($ex as $key => $v) {
                    // 启动单个渠道的循环
                    $page = 1;
                    $data = [
                        'page' => $page,
                        'channel_id' => $v
                    ];
                    dispatch(new GetOrderStatus($data, 'updateOrderStatus', 5))->onQueue('TaskGetOrderStatusDispose');
                    // return $this->returnMsg(200, '分页读取' . $page);
                }
            }
        }
        // 启动三个小时 一个循环
        $time = 3 * 60 * 60; // 3个小时更新一次
        if (date('H') > 21) {
            $times = date('Y-m-d 04:00:00', strtotime('+1 day'));
            $time = strtotime($times) - time();
        }
        // var_dump($time, 1111111111);
        dispatch(new GetOrderStatus(1, 'getAllOrderStatus', $time))->onQueue('TaskGetOrderStatusDispose');
        return $this->returnMsg(200, '运行完成');
    }

    // 主动请求第三方 获取订单的状态   一次跑一个月的数据
    public function updateOrderStatus($array = [])
    {
        // var_dump($data);
        // die();
        // 定时获取  每天 12点一次 下午七点运行一次
        $nums = 10;
        if (empty($page)) {
            $page = 1;
        }
        $this->log->info('订单获取数据' . time() . '手动推送数据页数' . $page . 'data参数' . json_encode($array));
        if (!empty($array['page'])) {
            $page = $array['page'];
        }
        if (empty($array['channel_id'])) {
            $this->log->info('跑的渠道参数为空' . json_encode($array));
            return $this->returnMsg(100, '参数运行失败', []);
        }
        // return '';
        $skip = ($page - 1) * $nums;
        $startTime = date('Y-m-d 00:00:00', strtotime('-30 day')); // 更新三十天内的订单信息
        $where[] = ['created_at', '>=', $startTime];
        $where[] = ['status', '<', 40];
        $where[] = ['sup_id', '=', $array['channel_id']];
        // 7 广州移动 3 省电信 6 感叹号
        // $whereIn = [7, 3, 6];
        // DB::connection()->enableQueryLog();
        $res = DB::table('orders')->where($where)->select(['id', 'ordersno', 'sup_orderno', 'status', 'sup_id'])->skip($skip)->take($nums)->orderBy('id', 'desc')->get();
        // $log = DB::getQueryLog();
        // var_dump($log);
        $this->log->info('查询参数:' . json_encode($where) . '返回参数' . json_encode($res));
        $model = new MainOrderRepostition();
        if ($res) {
            $res = json_decode(json_encode($res), true);
            foreach ($res as $key => $v) {
                $v = json_decode(json_encode($v), true); // 将订单处理下
                $return = $this->getOrderWay($v);
                if (empty($return)) {
                    continue;
                }
                // 将参数记录到 log日志中
                $this->log->info('更新状态时的得到的参数:' . json_encode($return));
                // var_dump($return);

                $datas = !empty($return['data'][0]) ? $return['data'][0] : [];
                if (!empty($datas) && !empty($datas['status'])) {
                    // $where = ['sup_orderno' => $datas['sup_order']];
                    // 查询条件可用上面 也可用这个
                    $where = ['ordersno' => $v['ordersno']];
                    $editData = [
                        'status' => $datas['status'],
                    ];
                    if ((!empty($datas['status']) && $datas['status'] == 20 && empty($datas['express_number']))) {
                        continue;
                    }
                    if (!empty($v['status']) && !empty($datas['status']) && $datas['status'] == $v['status'] && $v['status'] <= 40) {
                        continue;
                    }
                    if (!empty($datas['express_number'])) {
                        $editData['express_number'] = $datas['express_number'];
                        $editData['express_company'] = $datas['express_company'];
                    }
                    if (!empty($datas['iccid'])) {
                        $editData['iccid'] = $datas['iccid'];
                    }
                    if (!empty($datas['three_msg'])) {
                        $editData['three_msg'] = $datas['three_msg'];
                    }
                    // 串号
                    if (!empty($datas['imei'])) {
                        $editData['imei'] = $datas['imei'];
                    }
                    // 是否首冲
                    if (!empty($datas['first_status'])) {
                        $editData['first_status_desc'] = $datas['first_status'];
                    }
                    // 返回的解释
                    if (!empty($datas['order_desc'])) {
                        $editData['card_status_desc'] = $datas['order_desc'];
                    }
                    // 修改订单状态
                    $resa = $model->editOrderThree($where, $editData);
                    $this->log->info('更新状态时的得到的参数:' . json_encode($return) . '修改后的结果' . !empty($resa) ? json_encode($resa) : '未修改');
                }

                // 修改订单状态
            }
        }
        if (empty($res) || count($res) < $nums) {

            return $this->returnMsg(200, '运行完成');
        }
        // 分页10s 处理一次
        $page++;
        $data_array = [
            'page' => $page,
            'channel_id' => $array['channel_id'],
        ];
        dispatch(new GetOrderStatus($data_array, 'updateOrderStatus', 5))->onQueue('TaskGetOrderStatusDispose');
        return $this->returnMsg(200, '分页读取' . $page);
    }

    // 将渠道分开
    public function updateOrderStatus_manual($data, $channel_id = 0)
    {
        // 定时获取  每天 12点一次 下午七点运行一次
        $nums = 10;
        if (empty($page)) {
            $page = 1;
        }
        $this->log->info('人工订单获取数据' . time() . '手动推送数据页数' . $page . 'data参数' . json_encode($data));
        if (!empty($data['orderno'])) {
            $page = $data['orderno'];
        }
        $skip = ($page - 1) * $nums;
        $startTime = date('Y-m-d 00:00:00', strtotime('-3 day')); // 更新三天内的订单信息
        $where[] = ['created_at', '>=', $startTime];
        $where[] = ['status', '<', 50];
        // $where[] = ['sup_id', '=', 7];
        // 7 广州移动 3 省电信 6 感叹号
        $whereIn = [7, 3, 6];
        if (!empty($channel_id)) {
            $whereIn = [$channel_id];
        }

        // DB::connection()->enableQueryLog();
        $res = DB::table('order')->where($where)->whereIn('sup_id', $whereIn)->skip($skip)->take($nums)->orderBy('sup_id', 'desc')->get();
        // $log = DB::getQueryLog();
        // var_dump($log);
        $this->log->info('查询参数:' . json_encode($where) . '返回参数' . json_encode($res));
        $model = new MainOrderRepostition();
        if ($res) {
            $res = json_decode(json_encode($res), true);
            foreach ($res as $key => $v) {
                $v = json_decode(json_encode($v), true); // 将订单处理下
                $return = $this->getOrderWay($v);
                if (empty($return)) {
                    continue;
                }
                // 将参数记录到 log日志中
                $this->log->info('人工更新状态时的得到的参数:' . json_encode($return));
                // var_dump($return);

                $datas = !empty($return['data'][0]) ? $return['data'][0] : [];
                if (!empty($datas)) {
                    // $where = ['sup_orderno' => $datas['sup_order']];
                    // 查询条件可用上面 也可用这个
                    $where = ['orderno' => $v['orderno']];
                    $editData = [
                        'status' => $datas['status'],
                    ];
                    if ((!empty($datas['status']) && $datas['status'] == 20 && empty($datas['express_number']))) {
                        continue;
                    }
                    if (!empty($datas['express_number'])) {
                        $editData['express_number'] = $datas['express_number'];
                        $editData['express_company'] = $datas['express_company'];
                    }
                    if (!empty($datas['iccid'])) {
                        $editData['iccid'] = $datas['iccid'];
                    }
                    if (!empty($datas['three_msg'])) {
                        $editData['three_msg'] = $datas['three_msg'];
                    }
                    // 串号
                    if (!empty($datas['imei'])) {
                        $editData['imei'] = $datas['imei'];
                    }
                    // 是否首冲
                    if (!empty($datas['first_status'])) {
                        $editData['first_status_desc'] = $datas['first_status'];
                    }
                    // 修改订单状态
                    $resa = $model->editOrderThree($where, $editData);
                    $this->log->info('人工更新状态时的得到的参数:' . json_encode($return) . '修改后的结果' . !empty($resa) ? json_encode($resa) : '未修改');
                }

                // 修改订单状态
            }
        }
        if (empty($res) || count($res) < $nums) {
            $page = 0;
            // $times = date('Y-m-d 12:00:00', strtotime('+1 day'));
            // // 白天 3个小时更新一次
            // if (date('H') > 19) {
            //     $times = date('Y-m-d 19:00:00', strtotime('+1 day'));
            // }
            // $time = strtotime($times) - time();
            $time = 3 * 60 * 60; // 3个小时更新一次
            if (date('H') > 19) {
                $times = date('Y-m-d 07:00:00', strtotime('+1 day'));
                $time = strtotime($times) - time();
            }
            // var_dump($time, 1111111111);
            // dispatch(new BigData(1, 'updateOrderStatus', $time))->onQueue('TaskBigDataDispose');
            return $this->returnMsg(200, '运行完成');
        }
        // 分页10s 处理一次
        $page++;
        dispatch(new BigData($page, 'updateOrderStatus', 5))->onQueue('TaskBigDataDispose');
        return $this->returnMsg(200, '分页读取' . $page);
    }

    public function getOrderWay($order)
    {
        $model = new WayRepository();
        $resChannelModel = $model->getOne(['id' => $order['sup_id']]);
        if (!$resChannelModel) {
            return [];
        }
        if ($resChannelModel) {
            $resChannelModel = json_decode(json_encode($resChannelModel), true);
        }
        $order['model'] = $order['sup_id'];
        $data = array_merge($order, $resChannelModel);
        $model = new Transfer();
        return $model->queryOneOrder($data);
    }

    // 手动同步数据  激活 发货 字段
    public function getOrderUpOrders($where, $page = 1)
    {
        $read = ($page - 1) * 50;
        if (!empty($where['page'])) {
            $read = ($where['page'] - 1) * 50;
            $page = $where['page'];
        }
        $this->logOrdersOld->info('数据查询参数:' . jsonEncodeMsg($where));
        // 10s 一百条
        // DB::connection()->enableQueryLog();
        $datas = [];
        $datas = DB::table('order_info')->where(['status' => 40])->offset($read)->limit(50)->orderBy('id', 'ASC')->get();
        // $log = DB::getQueryLog();
        // var_dump($datas);
        $res = ['status' => 100, '数据已存在'];
        $model = new OrdersRepository();
        if ($datas) {
            foreach ($datas as $key => $v) {
                if (!empty($v->id)) {
                    unset($v->id);
                }
                $isTrue = $model->getOne(['ordersno' => $v->orderno]);
                if ($isTrue) {
                    // $v = json_decode(json_encode($v), true);
                    $where = ['ordersno' => $v->orderno];
                    $update = [
                        'deliver_at' => $v->deliver_at,
                        'sign_at' => $v->sign_at,
                        'activat_at' => $v->activat_at,
                    ];
                    if ($isTrue['status'] != 40) {
                        $update['status'] = 40;
                        $update['status_desc'] = '已激活';
                    }
                    $res = $model->editOrderAct($where, $update);
                }
                if (!empty($update)) {
                    $this->logOrdersOld->info('参数:' . jsonEncodeMsg($v) . '修改数据:' . jsonEncodeMsg($update) . '返回结果:' . jsonEncodeMsg($res));
                } else {
                    $this->logOrdersOld->info('参数:' . jsonEncodeMsg($v) . '返回结果:' . jsonEncodeMsg($res));
                }
            }
            // 启动定时 任务
            $page++;
            $isEnd = json_decode(json_encode($datas), true);
            if (!empty($isEnd)) {
                $datas = [];
                dispatch(new GetOrderStatus(['page' => $page], 'getOrderUpOrders', 3))->onQueue('TaskGetOrderStatusDispose'); // 手动修改订单的达人信息
            }
        }
        return 1;
    }

    // 手动 跑订单的数据  将order里面的数据 跑到 orders 里面
    public function getOrderUpOrders_back($where, $page = 1)
    {
        $read = ($page - 1) * 50;
        if (!empty($where['page'])) {
            $read = ($where['page'] - 1) * 50;
            $page = $where['page'];
        }
        $this->logOrdersOld->info('数据查询参数:' . jsonEncodeMsg($where));
        // 10s 一百条
        // DB::connection()->enableQueryLog();
        $datas = [];
        $datas = DB::table('order')->offset($read)->limit(50)->orderBy('id', 'ASC')->get();
        // $log = DB::getQueryLog();
        // var_dump($log);
        $res = ['status' => 100, '数据已存在'];
        $model = new OrdersOldRepository();
        if ($datas) {
            foreach ($datas as $key => $v) {
                if (!empty($v->id)) {
                    unset($v->id);
                }
                $isTrue = $model->getOne(['ordersno' => $v->orderno]);
                if (!$isTrue) {
                    $v = json_decode(json_encode($v), true);
                    $res = $model->editOrderUpOrders($v);
                }
                $this->logOrdersOld->info('参数:' . jsonEncodeMsg($v) . '返回结果:' . jsonEncodeMsg($res));
            }
            // 启动定时 任务
            $page++;
            $isEnd = json_decode(json_encode($datas), true);
            if (!empty($isEnd)) {
                $datas = [];
                dispatch(new GetOrderStatus(['page' => $page], 'getOrderUpOrders', 3))->onQueue('TaskGetOrderStatusDispose'); // 手动修改订单的达人信息
            }
        }
        return 1;
    }

    public function varOrderUpOrders($where, $page = 1)
    {
        $read = ($page - 1) * 50;
        if (!empty($where['page'])) {
            $read = ($where['page'] - 1) * 50;
            $page = $where['page'];
        }
        // $read = 0;
        $this->logOrdersVar->info('数据查询参数:' . jsonEncodeMsg($where));
        // 10s 一百条
        // DB::connection()->enableQueryLog();
        $datas = [];
        // $where = ['orderno' => 'HK_4960600468573848985'];
        // $datas = DB::table('order')->offset($read)->limit(50)->orderBy('id', 'ASC')->get();
        $ordersModel = new OrdersRepository();
        $whereOrders = [];
        $whereOrders['between'] = ['orders.created_at' => ['2023-01-10 22:00:00', '2023-01-11 23:00:00']];
        $whereOrders['join'] = [
            ['table' => 'orders_user', 'left' => 'id', 'right' => 'orders.orders_user_id']
        ];
        // $whereOrders['where'] = ['ordersno' => 'HK_20230107142648160668306607'];
        $whereOrders['limit']['start'] = $read;
        $whereOrders['limit']['number'] = 50;
        $datas = $ordersModel->index($whereOrders);
        // $log = DB::getQueryLog();
        // var_dump($log);
        // var_dump($datas);
        $res = ['status' => 100, '数据已存在'];
        $model = new OrdersOldRepository();
        if (!empty($datas['data'])) {
            foreach ($datas['data'] as $key => $v) {
                $res = ['status' => 100, '数据已存在'];
                if (!empty($v['id'])) {
                    unset($v['id']);
                }
                // var_dump($v);
                $isTrue = [];
                // $isTrue = $model->getOne(['ordersno' => $v['ordersno']]);
                $isTrue = DB::table('orders_old')->where(['ordersno' => $v['ordersno']])->first();
                // var_dump($isTrue);
                $isTrue = json_decode(json_encode($isTrue), true);
                // var_dump($isTrue);
                if (empty($isTrue)) {
                    // var_dump(11111);
                    $v = json_decode(json_encode($v), true);
                    $res = $model->editOrderUpOrders($v);
                }
                // $v = json_decode(json_encode($v), true);
                // $res = $model->editOrderUpOrders($v);
                // if (empty($isTrue) || $isTrue != 1) {
                //     $this->isManyOrders->info('参数' . jsonEncodeMsg($v) . '返回结果' . ($isTrue));
                // }
                $this->logOrdersVar->info('参数:' . jsonEncodeMsg($v) . '返回结果:' . jsonEncodeMsg($res));
            }
            // 启动定时 任务
            $page++;
            $isEnd = json_decode(json_encode($datas), true);
            if (!empty($isEnd)) {
                $datas = [];
                dispatch(new GetOrderStatus(['page' => $page], 'varOrderUpOrders', 3))->onQueue('TaskGetOrderStatusDispose'); // 手动修改订单的达人信息
            }
        }
        return 1;
    }

    // 跟抖音同步订单
    public function douyinPaySyncOrder($where)
    {
        $wheres = [
            'orderno' => $where['orderno']
        ];
        $models = new TouTiaoUserOrderRepository();

        $douYinUserOrder = $models->getOne($wheres);
        // $logs = DB::getQueryLog();
        // var_dump($logs);
        // die();
        if (!$douYinUserOrder) {
            return $this->returnMsg(106, '未查询该订单');
        }
        $modelUser = new TouTiaoUser();
        $whereUser = [
            'id' => $douYinUserOrder->user_id
        ];
        $douYinUser = $modelUser->getOne($whereUser);
        if (empty($douYinUser) || empty($douYinUser->openid)) {
            return $this->returnMsg(102, '未查询到用户信息');
        }
        // 查询订单 和商品
        $ordersModel = new OrdersRepository();
        $orders = $ordersModel->getOne($where);
        if (!$orders) {
            return $this->returnMsg(104, '未查询到订单');
        }
        $douyinConfig = DB::table('app_douyin_config')->where(['shop_id' => $douYinUser->shop_id])->first();
        // var_dump($douyinConfig, 5555555555);
        if (empty($douyinConfig) || empty($douyinConfig->app_key)) {
            return $this->returnMsg(100, '未查询到订单,请重新下单');
        }
        // var_dump($orders);
        // 查询商品
        // $whereGoods = [
        //     'id' => $orders['goods_id']
        // ];
        // $goodsRes = $this->goodsModel->getOne($whereGoods, ['id', 'main_pic']);
        // if (!$goodsRes) {
        //     return $this->returnMsg(100, '未查询到用户购买的商品');
        // }
        // $url = $_SERVER['HTTP_HOST'];
        // // var_dump($url);
        // $path = 'http://';
        // if ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ||  $_SERVER['SERVER_PORT'] == '443') {
        //     $path = 'https://';
        // }
        $path = 'http://adminnew.chenqiwangluo.com';
        $model = new douyinPayModel();
        $payData = [
            'app_id' => $douyinConfig->app_key,
            'app_secret' => $douyinConfig->app_secret,
            'out_order_no' => $douYinUserOrder->orderno,
            'total_amount' => $douYinUserOrder->money,
            'subject' => $orders['goods_name'],
            'body' => $orders['goods_name'],
            'access_token_json' => $douyinConfig->parame,
            'open_id' => $douYinUser->openid,
            'path' => 'pages/goodsDetail/goodsDetail?id=' . $orders['goods_id'],
            'goods_id' => $orders['goods_id'],
            'img' => $douYinUserOrder->main_pic,
            'shop_id' => $douYinUserOrder->shop_id,
            'status' => $douYinUserOrder->status
        ];
        // var_dump($payData);
        // die();
        $res = $model->pushOrder($payData);
        $this->log->info('抖音同步信息data参数' . json_encode($payData) . '返回结果:' . json_encode($res));
        return $res;
    }

    public function douyinRefundSyncOrder($where)
    {
        $wheres = [
            'orderno' => $where['orderno']
        ];
        $models = new TouTiaoUserOrderRepository();
        $douYinUserOrder = $models->getOne($wheres);
        if (!$douYinUserOrder) {
            return $this->returnMsg(103, '未查询到订单');
        }
        $modelUser = new TouTiaoUser();
        $whereUser = [
            'id' => $douYinUserOrder->user_id
        ];
        $douYinUser = $modelUser->getOne($whereUser);
        if (empty($douYinUser) || empty($douYinUser->openid)) {
            return $this->returnMsg(102, '未查询到用户信息');
        }
        // 查询订单 和商品
        $ordersModel = new OrdersRepository();
        $orders = $ordersModel->getOne($where, ['ordersno', 'status']);
        if (!$orders) {
            return $this->returnMsg(104, '未查询到订单');
        }
        $douyinConfig = DB::table('app_douyin_config')->where(['shop_id' => $douYinUser->shop_id])->first();
        // var_dump($douyinConfig, 5555555555);
        if (empty($douyinConfig) || empty($douyinConfig->app_key)) {
            return $this->returnMsg(100, '未查询到订单,请重新下单');
        }
        // 根据orders_status
        $str = '用户取消退款';
        if (!empty($douYinUserOrder->status) && $douYinUserOrder->status == 8 && $orders->status > 40) {
            $str = '审核失败退款';
        }
        $array = [
            'app_id' => $douyinConfig->app_key,
            'ordersno' => $douYinUserOrder->orderno,
            'money' => $douYinUserOrder->money,
            'out_refund_no' => $douYinUserOrder->out_refund_no,
            'reason' => $str,
        ];

        // var_dump($array);
        // die();
        $model = new douyinPayModel();
        $res = $model->refundOrder($array);
        $this->log->info('抖音退款data参数' . json_encode($array) . '返回结果:' . json_encode($res));
        return $res;
    }
}
